package org.yunai.swjg.server.core.service;

import org.yunai.swjg.server.rpc.message.C_S.C_S_LoginReq;
import org.yunai.swjg.server.rpc.message.C_S.C_S_PlayerCreateReq;
import org.yunai.swjg.server.rpc.message.C_S.C_S_SceneEnterReq;
import org.yunai.swjg.server.rpc.message.C_S.C_S_SceneSwitchReq;
import org.yunai.yfserver.message.IMessage;

/**
 * 在线状态管理器
 * User: yunai
 * Date: 13-4-24
 * Time: 下午10:37
 */
public class OnlineStateService {

    /**
     * 在线状态
     */
    private OnlineState state;
    /**
     * 游戏状态
     */
    private GamingState gamingState;

    public OnlineStateService() {
        this.state = OnlineState.unconnected;
        this.gamingState = GamingState.NULL;
    }

    public void setState(OnlineState state) {
        this.state = state;
    }

    public OnlineState getState() {
        return state;
    }

    public void setGamingState(GamingState gamingState) {
        this.gamingState = gamingState;
    }

    public GamingState getGamingState() {
        return gamingState;
    }

    public boolean validateMessage(IMessage msg) {
        final short code = msg.getCode();
        switch (this.state) {
            case connected: // 只接收登录消息
                return code == C_S_LoginReq.CODE;
            case temp_authed: // 不接收任何消息
                return false;
            case authed: // 不接收任何消息
                return false;
            case client_create_roleing: // 只接收创建角色消息
                return code == C_S_PlayerCreateReq.CODE;
            case client_create_roled: // 不接收任何消息
                return false;
            case load_roleing: // 不接收任何消息
                return false;
            case load_roled: // 只接收进入场景消息
                return code == C_S_SceneEnterReq.CODE;
            case enter_sceneing: // 不接收任何消息
                return false;
            case gaming: // 不接收登录消息、创建角色消息、入场景消息
                return validateMessageInGaming(msg);
            case logouting: // 不接收任何消息
                return false;
            case logouted: // 不接收任何消息
                return false;
            default:
                throw new RuntimeException("error online.state.");
        }
    }

    private boolean validateMessageInGaming(IMessage msg) {
        final short code = msg.getCode();
        if (code == C_S_LoginReq.CODE || code == C_S_PlayerCreateReq.CODE || code == C_S_SceneEnterReq.CODE) {
            return false;
        }
        switch (gamingState) {
            case SWITCH_NORMAL_SCENE: return code != C_S_SceneSwitchReq.CODE;
            // TODO 还有几个状态
            default: return true;
        }
    }
}
